<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>青云教育系统 - 教师端</title>
    <link rel="stylesheet" href="../../teacher.css">
</head>
<body>
    <div class="layout">
        <aside class="sidebar">
            <div class="brand">青云教育 · 教师端</div>
            <nav class="menu" id="menu">
                <button class="menu-item" data-view="profile" data-url="/index">教员信息及考勤</button>
                <button class="menu-item" data-view="schedule" data-url="/schedule">教师课表</button>
                <button class="menu-item" data-view="password" data-url="/password">修改密码</button>
                <button class="menu-item active" data-view="students" data-url="/students">学生信息</button>
                <button class="menu-item" data-view="upload" data-url="/postmaterial">上传资料</button>
                <button class="menu-item" data-view="download" data-url="/download">下载资料</button>
                <button class="menu-item" data-view="mymaterials" data-url="/mymaterials">我的资料</button>
                
                
            </nav>
        </aside>
        <main class="content">
            <header class="topbar">
                <div class="left">
                    <h1 id="view-title">学生信息</h1>
                </div>
                <div class="right">
                    <div class="user-info">
                        <img id="user-avatar" class="user-avatar" src="" alt="用户头像">
                        <span id="teacher-name" class="user-name"></span>
                    </div>
                    <button id="logoutBtn" class="btn btn-secondary">退出登录</button>
                </div>
            </header>

            <section id="view-students" class="view" style="display:block;">
                <div class="card">
                    <div class="card-header">我的学生</div>
                    <div class="card-body">
                        <div class="filters">
                            <input type="text" id="studentSearch" placeholder="输入学生姓名搜索">
                            <button id="searchStudentBtn" class="btn btn-primary">搜索</button>
                            <button id="refreshStudentBtn" class="btn btn-secondary">刷新</button>
                        </div>
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>学生姓名</th>
                                    <th>年级</th>
                                    <th>联系方式</th>
                                    <th>剩余课时</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="studentTableBody"></tbody>
                        </table>
                        <div id="studentEmpty" class="empty" style="display:none;">暂无学生信息</div>
                    </div>
                </div>
            </section>
        </main>
    </div>

    <script src="../../teacher.js"></script>
    <script>
        // 确保退出登录功能正常工作
        document.addEventListener('DOMContentLoaded', function(){
            // 绑定退出登录按钮事件（如果teacher.js没有绑定成功）
            const logoutBtn = document.getElementById('logoutBtn');
            if (logoutBtn && !logoutBtn.hasAttribute('data-bound')) {
                logoutBtn.setAttribute('data-bound', 'true');
                logoutBtn.addEventListener('click', function(e) {
                    console.log('退出登录按钮被点击（来自students页面）');
                    e.preventDefault();
                    if (typeof logout === 'function') {
                        logout();
                    } else {
                        console.error('logout函数未定义');
                    }
                });
            }
            
            // 菜单跳转逻辑
            const menu = document.getElementById('menu');
            if (menu) {
                console.log('菜单元素找到，绑定点击事件');
                menu.addEventListener('click', function(e){
                    console.log('菜单被点击');
                    const btn = e.target.closest('.menu-item');
                    if(!btn) {
                        console.log('没有找到菜单项');
                        return;
                    }
                    const view = btn.getAttribute('data-view');
                    console.log('点击的菜单项:', view);
                    
                    if(view === 'schedule') {
                        console.log('跳转到课表页面');
                        window.location.href = '/teacher/schedule';
                    }
                    else if(view === 'password') {
                        console.log('跳转到修改密码页面');
                        window.location.href = '/teacher/password';
                    }
                    else if(view === 'profile') {
                        console.log('跳转到首页');
                        window.location.href = '/index.html';
                    }
                    else if(view === 'upload') {
                        console.log('跳转到上传资料页面');
                        window.location.href = '/teacher/postmaterial';
                    }
                    else if(view === 'download') {
                        console.log('跳转到下载资料页面');
                        window.location.href = '/teacher/downloadmaterial';
                    }
                    else if(view === 'mymaterials') {
                        console.log('跳转到我的资料页面');
                        window.location.href = '/teacher/mymaterials/';
                    }
                    else if(view === 'myfeedback') {
                        console.log('跳转到我的反馈页面');
                        window.location.href = '/teacher/myfeedback';
                    }
                    else if(view === 'students') {
                        console.log('刷新学生信息');
                        // 点击学生信息菜单时调用接口
                        loadStudentInfo();
                    }
                    else if(view === 'feedback') {
                        console.log('跳转到课堂反馈页面');
                        window.location.href = '/teacher/feedback';
                    }
                    else {
                        console.log('未知的菜单项:', view);
                    }
                });
            } else {
                console.error('菜单元素未找到！');
            }
            
            // 页面加载时也调用一次学生信息接口
            loadStudentInfo();
            
            // 绑定搜索和刷新按钮
            document.getElementById('searchStudentBtn').addEventListener('click', function() {
                const keyword = document.getElementById('studentSearch').value.trim();
                if (keyword) {
                    searchStudents(keyword);
                } else {
                    loadStudentInfo(); // 如果搜索关键词为空，则加载全部学生
                }
            });
            
            document.getElementById('refreshStudentBtn').addEventListener('click', function() {
                document.getElementById('studentSearch').value = '';
                loadStudentInfo();
            });
            
            // 搜索学生功能
            async function searchStudents(keyword) {
                try {
                    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                    const token = userInfo.token;
                    
                    if (!token) {
                        console.error('未找到用户token');
                        return;
                    }
                    
                    console.log('搜索学生:', keyword);
                    
                    // 调用搜索接口（这里假设后端支持搜索参数）
                    const response = await fetch(`http://localhost:8081/student/studentInfo?keyword=${encodeURIComponent(keyword)}`, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': token
                        }
                    });
                    
                    if (response.ok) {
                        const result = await response.json();
                        console.log('搜索学生接口返回:', result);
                        
                        if (result.success && result.data) {
                            displayStudentInfo(result.data);
                        } else {
                            console.error('搜索失败:', result.errorMsg);
                            showEmptyMessage('搜索失败');
                        }
                    } else {
                        console.error('搜索请求失败:', response.status);
                        showEmptyMessage('搜索请求失败');
                    }
                } catch (error) {
                    console.error('搜索学生异常:', error);
                    showEmptyMessage('搜索时发生错误');
                }
            }
            
            // 加载学生信息
            async function loadStudentInfo() {
                try {
                    // 获取用户token
                    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                    const token = userInfo.token;
                    
                    if (!token) {
                        console.error('未找到用户token');
                        return;
                    }
                    
                    console.log('调用学生信息接口:', '/student/studentInfo');
                    
                    // 调用后端接口
                    const response = await fetch('http://localhost:8081/student/studentInfo', {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': token
                        }
                    });
                    
                    if (response.ok) {
                        const result = await response.json();
                        console.log('学生信息接口返回:', result);
                        
                        if (result.success && result.data) {
                            displayStudentInfo(result.data);
                        } else {
                            console.error('接口返回失败:', result.errorMsg);
                            showEmptyMessage('获取学生信息失败');
                        }
                    } else {
                        console.error('接口请求失败:', response.status);
                        showEmptyMessage('网络请求失败');
                    }
                } catch (error) {
                    console.error('调用学生信息接口异常:', error);
                    showEmptyMessage('加载学生信息时发生错误');
                }
            }
            
            // 显示学生信息
            function displayStudentInfo(studentList) {
                const tbody = document.getElementById('studentTableBody');
                const empty = document.getElementById('studentEmpty');
                
                tbody.innerHTML = '';
                empty.style.display = 'none';
                
                if (!studentList || studentList.length === 0) {
                    showEmptyMessage('暂无学生信息');
                    return;
                }
                
                // 保存 学生姓名 -> 学生ID 的映射
                const nameIdMap = {};
                // 渲染学生列表
                studentList.forEach(student => {
                    if (student && student.name) {
                        nameIdMap[student.name] = student.studentId || student.id;
                    }
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td>${student.name || '未设置'}</td>
                        <td>${student.grade || '未设置'}</td>
                        <td>${student.phone || '未设置'}</td>
                        <td>${student.remainingHours || 0}</td>
                        <td>
                            <div class="inline">
                                <button class="btn btn-secondary btn-view-schedule" data-student='${JSON.stringify({ id: (student.studentId || student.id), name: student.name }).replace(/'/g, "&apos;")}'>查看课程安排</button>
                                <button class="btn btn-primary btn-open-feedback-page" data-sid='${(student.studentId || student.id) || ''}'>课堂反馈</button>
                            </div>
                        </td>
                    `;
                    tbody.appendChild(tr);
                });

                // 写入本地存储
                try {
                    localStorage.setItem('studentNameIdMap', JSON.stringify(nameIdMap));
                } catch (e) {
                    console.warn('保存学生映射到localStorage失败', e);
                }

                // 绑定查看课程安排按钮
                tbody.querySelectorAll('.btn-view-schedule').forEach(btn => {
                    btn.addEventListener('click', function(){
                        const data = this.getAttribute('data-student');
                        try{
                            const student = JSON.parse(data.replace(/&apos;/g, "'"));
                            openStudentScheduleDialog(student);
                        }catch(e){
                            console.error('解析学生信息失败', e);
                        }
                    });
                });

                // 绑定课堂反馈跳转按钮
                tbody.querySelectorAll('.btn-open-feedback-page').forEach(btn => {
                    btn.addEventListener('click', function(){
                        const sid = this.getAttribute('data-sid');
                        if(!sid){ return; }
                        // 从同一行取出学生名以便下页直接展示
                        try{
                            const tdName = this.closest('tr')?.children?.[0]?.textContent?.trim() || '';
                            localStorage.setItem('currentFeedbackStudent', JSON.stringify({ id: sid, name: tdName }));
                        }catch(e){}
                        window.location.href = `/teacher/feedback/?id=${encodeURIComponent(sid)}`;
                    });
                });
            }

            // 打开学生课程安排弹层
            function openStudentScheduleDialog(student){
                ensureScheduleDialog();
                const dialog = document.getElementById('studentScheduleDialog');
                const title = dialog.querySelector('.dialog-title');
                const listEl = document.getElementById('studentScheduleList');
                title.textContent = `课程安排 - ${student.name || ''}`;
                listEl.innerHTML = '<div class="empty">加载中...</div>';
                dialog.style.display = 'block';
                loadStudentSchedule(student.id);
            }

            // 创建弹层结构（若不存在）
            function ensureScheduleDialog(){
                if(document.getElementById('studentScheduleDialog')) return;
                const wrapper = document.createElement('div');
                wrapper.id = 'studentScheduleDialog';
                wrapper.style.position = 'fixed';
                wrapper.style.left = '0';
                wrapper.style.top = '0';
                wrapper.style.right = '0';
                wrapper.style.bottom = '0';
                wrapper.style.background = 'rgba(0,0,0,.35)';
                wrapper.style.display = 'none';
                wrapper.style.zIndex = '1000';
                wrapper.innerHTML = `
                    <div class="card" style="width: 860px; max-width: 92vw; margin: 10vh auto;">
                        <div class="card-header" style="display:flex;align-items:center;justify-content:space-between;">
                            <div class="dialog-title">课程安排</div>
                            <button id="closeStudentScheduleDialog" class="btn btn-secondary">关闭</button>
                        </div>
                        <div class="card-body">
                            <div id="studentScheduleList" class="list"></div>
                            <div id="studentScheduleEmpty" class="empty" style="display:none;">暂无课程安排</div>
                        </div>
                    </div>`;
                document.body.appendChild(wrapper);
                document.getElementById('closeStudentScheduleDialog').addEventListener('click', function(){
                    wrapper.style.display = 'none';
                });
                wrapper.addEventListener('click', function(e){
                    if(e.target === wrapper) wrapper.style.display = 'none';
                });
            }

            // 加载学生课程安排
            async function loadStudentSchedule(studentId){
                const listEl = document.getElementById('studentScheduleList');
                const emptyEl = document.getElementById('studentScheduleEmpty');
                listEl.innerHTML = '';
                emptyEl.style.display = 'none';
                try{
                    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                    const token = userInfo.token;
                    if(!token){ throw new Error('未登录'); }
                    // 接口（按学生ID）：/schedule/queryStudentSchedule?studentId=xx
                    const res = await fetch(`http://localhost:8081/schedule/queryStudentSchedule?studentId=${studentId}`, {
                        headers: { 'Authorization': token }
                    });
                    if(!res.ok){ throw new Error('网络错误'); }
                    const data = await res.json();
                    const list = (data && data.data) ? data.data : [];
                    if(!list.length){ emptyEl.style.display='block'; return; }
                    renderStudentSchedule(list);
                }catch(err){
                    listEl.innerHTML = '<div class="empty">加载失败，请稍后重试</div>';
                    console.error('加载学生课程安排失败', err);
                }
            }

            // 渲染学生课程安排（显示课程名 + 时间 + 地点，并美化排版）
            function renderStudentSchedule(list){
                const listEl = document.getElementById('studentScheduleList');
                const emptyEl = document.getElementById('studentScheduleEmpty');
                listEl.innerHTML = '';
                emptyEl.style.display = 'none';

                // 注入一次性样式（仅本弹层内使用）
                if(!document.getElementById('studentScheduleStyles')){
                    const style = document.createElement('style');
                    style.id = 'studentScheduleStyles';
                    style.textContent = `
                        #studentScheduleList { display: grid; grid-template-columns: 1fr; gap: 12px; }
                        #studentScheduleList .schedule-item { 
                            border: 1px solid #e5e7eb; border-radius: 10px; padding: 12px 14px; background: #fff; 
                            box-shadow: 0 1px 2px rgba(0,0,0,0.04);
                        }
                        #studentScheduleList .item-header { display:flex; justify-content:space-between; align-items:center; margin-bottom: 8px; }
                        #studentScheduleList .course { font-weight: 600; color: #111827; font-size: 15px; }
                        #studentScheduleList .time { color: #374151; font-size: 14px; }
                        #studentScheduleList .item-body { color:#6b7280; font-size: 13px; }
                        #studentScheduleList .place { padding-left: 18px; position: relative; }
                        #studentScheduleList .place:before { content: ""; position: absolute; left: 0; top: 5px; width: 10px; height: 10px; border-radius: 50%; background: #60a5fa; }
                        /* 始终单列竖排 */
                    `;
                    document.head.appendChild(style);
                }
                // 保障前端排序：日期升序、开始时间升序
                const sorted = (list || []).slice().sort((a,b) => {
                    const ad = (a.teachDate || '').toString();
                    const bd = (b.teachDate || '').toString();
                    if (ad !== bd) return ad.localeCompare(bd);
                    const at = (a.startTime || '').toString();
                    const bt = (b.startTime || '').toString();
                    return at.localeCompare(bt);
                });
                sorted.forEach(item => {
                    const div = document.createElement('div');
                    div.className = 'schedule-item';
                    const dateStr = (item.teachDate || '').toString().slice(0,10);
                    const startTime = item.startTime || '';
                    const endTime = item.endTime || '';
                    const place = item.place || '地点未设置';
                    const courseName = item.courseName || '课程';
                    div.innerHTML = `
                        <div class="item-header">
                            <div class="course">${courseName}</div>
                            <div class="time">${dateStr} ${startTime} - ${endTime}</div>
                        </div>
                        <div class="item-body">
                            <div class="place">${place}</div>
                        </div>`;
                    listEl.appendChild(div);
                });
            }
            
            // 格式化科目显示
            function formatSubjects(subjects) {
                if (!subjects || !Array.isArray(subjects) || subjects.length === 0) {
                    return '未设置';
                }
                return subjects.join('、');
            }
            
            // 显示空状态消息
            function showEmptyMessage(message) {
                const tbody = document.getElementById('studentTableBody');
                const empty = document.getElementById('studentEmpty');
                
                tbody.innerHTML = '';
                empty.textContent = message;
                empty.style.display = 'block';
            }
        });
    </script>
</body>
</html>

